package com.heatingcharge.security;

import cn.hutool.core.util.ObjectUtil;
import com.heatingcharge.entity.sys.SysUser;
import com.heatingcharge.service.sys.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description: heating_charge_server
 * User: Devin
 * Date: 2019-07-04
 * Time: 11:33
 */
@Slf4j
@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    ISysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user=sysUserService.findByName(username);
        if (ObjectUtil.isNull(user)){
            log.info("登录用户：" + username + " 不存在");
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        // 获取用户拥有的角色
        // 用户权限列表，根据用户拥有的权限标识与如 @PreAuthorize("hasAuthority('sys:menu:view')") 标注的接口对比，决定是否可以调用接口

        // 权限集合
        Set<String> permissions=sysUserService.findPermsByUserId(user.getId());
        // 角色集合
//        Set<String> roleIds=sysUserService.findRoleIdByUserId(user.getId());
//        permissions.addAll(roleIds);
        Collection<? extends GrantedAuthority> authorities= AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        return new JwtUser(user.getId(),user.getUsername(),user.getPassword(),user.getRealName(),user.getStatus(),authorities);
    }
}
